package com.geen.tuoke.ui.activity

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.geen.tuoke.MyApplication
import com.geen.tuoke.R
import com.geen.tuoke.base.BaseActivity
import com.geen.tuoke.bean.TaskDetailInfo
import com.geen.tuoke.bean.TaskInfo
import com.geen.tuoke.databinding.ActivityTaskDetailBinding
import com.geen.tuoke.ui.adapter.TaskDetailAdapter
import com.geen.tuoke.ui.dialog.*
import com.geen.tuoke.ui.popupwindow.TaskFuncPopup
import com.geen.tuoke.ui.popupwindow.TaskPhonePopup
import com.geen.tuoke.ui.viewmodel.CustomerViewModel
import com.geen.tuoke.ui.viewmodel.PhoneFragmentViewModel
import com.geen.tuoke.utils.PhoneStateReceiver
import com.geen.tuoke.utils.ext.dp2px
import com.geen.tuoke.widget.popupwindow.HorizontalGravity
import com.geen.tuoke.widget.popupwindow.VerticalGravity
import com.mylhyl.acp.Acp
import com.mylhyl.acp.AcpListener
import com.mylhyl.acp.AcpOptions
import com.qmuiteam.qmui.kotlin.onClick
import kotlinx.android.synthetic.main.include_toolbar.*
import kotlinx.android.synthetic.main.item_task_search.*

/**
 * @Desc 任务详情页面
 */
class TaskDetailActivity : BaseActivity<PhoneFragmentViewModel, ActivityTaskDetailBinding>() {

    //是否是自动拨打模式
    var isAutoCallMode = MutableLiveData<Boolean>(true)

    //当前选择到的拨号位置
    var curPosition = 0

    //是否添加客户【添加客户后  返回页面的时候 需要重新走一下自动打电话逻辑  】
    var isAddCustomerMode = false

    lateinit var adapter: TaskDetailAdapter

    //0 未接通 1接通    -1 空号
    var callOutResultByNet = 0

    private val timeIntervalDialog: DialogTimeInterval by lazy {
        DialogTimeInterval(this) {
            mViewModel.updatePhoneTaskInterval(taskInfo.id, it)
        }
    }


    private val addTaskPhoneDialog: DialogAddTaskPhone by lazy {
        DialogAddTaskPhone(this, taskId = taskInfo.id) {
            mViewModel.addPhoneTask(it)
        }
    }

    private val autoCallDialog: DialogTaskPhoneAutoCall by lazy {
        DialogTaskPhoneAutoCall(this, {
            isAutoCallMode.value = false
        }, {
            curPosition++
            val item = adapter.data.getOrNull(curPosition)
            if (item == null) {
                //没有下一个了
                ToastUtils.showShort("没有下一个了  任务已完成")
            } else {
                callPhoneByNet(item)
            }
        }, onClickCustomer = {
            isAddCustomerMode = true
            //点击添加客户
            val taskDetailInfo = mViewModel.detailsList.value?.getOrNull(curPosition)
            taskDetailInfo?.let {
                if (it.isClient == 1) {
                    mViewModel.getCustomInfoById(it.clientId)
                } else {
                    AddOrEditCustomerActivity.start(this, null)
                }
            }

        }, updateTask = {
            //更新
            val taskDetailInfo = mViewModel.detailsList.value?.getOrNull(curPosition)
            taskDetailInfo?.let { detail ->
                it.id = detail.id
                mViewModel.updateTask(it)
            }
        })

    }

    private val createCallTaskDialog: DialogTaskPhoneCreateCallTask by lazy {
        DialogTaskPhoneCreateCallTask(this) {
            isAutoCallMode.value = true
            it.id = taskInfo.id
            mViewModel.recreatePhoneTask(it)
        }

    }


    private val taskFuncPopup: TaskFuncPopup by lazy {
        TaskFuncPopup(this, {
            mViewModel.getPhoneTaskDetailById(taskInfo.id, isCallTimeSort = true)
        }, {
            mViewModel.getPhoneTaskDetailById(taskInfo.id, isDurationSort = true)
        }).createPopup<TaskFuncPopup>()
    }


    //时间间隔相关
    var timeInterval = 10

    private val taskInfo: TaskInfo by lazy {
        (intent.getSerializableExtra("info") as TaskInfo).apply {
            mViewModel.timeInterval.value = this.intervalTime
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        with(mBinding) {
            lifecycleOwner = this@TaskDetailActivity
            data = taskInfo

            tvTimeInterval.onClick {
                timeIntervalDialog.setData(timeInterval).showDialog()
            }

            ivAdd.onClick {
                addTaskPhoneDialog.showDialog()
            }
            ivBack.onClick {
                finish()
            }

            ivFilter.onClick {
                taskFuncPopup.showAtAnchorView(
                    ivFilter, VerticalGravity.BELOW,
                    HorizontalGravity.ALIGN_RIGHT,
                    0, dp2px(10f)
                )
            }

            mBinding.tvAutoSetting.onClick {
                if (isAutoCallMode.value!!) {
                    //自动拨号模式

                    val item = adapter.data.getOrNull(curPosition)
                    if (item == null) {
                        //没有下一个了
                        ToastUtils.showShort("没有下一个了  完成全部了")
                    } else {
                        callPhoneByNet(item)
                    }

                } else {
                    //重新拨号模式
                    createCallTaskDialog.showAutoDialog()
                }
            }

        }


        initRV()
        checkPermissions()
        registerReceiverByPhoneState()
        //任务完成后 需要显示新建任务弹窗
        if (taskInfo.finishStatus == 1) {
            createCallTaskDialog.showAutoDialog()
        }

    }


    override fun initData() {

        val customerViewModel = ViewModelProvider(this).get(CustomerViewModel::class.java)
        customerViewModel.getLabelList()

        customerViewModel.labelList.observe(this) {
            autoCallDialog.setLabelData(it)
            createCallTaskDialog.setLabelData(it)
        }

        isAutoCallMode.observe(this) {
            mBinding.tvAutoSetting.text = if (it) "自动拨号" else "重新拨号"
        }

        mViewModel.reCreateTaskResult.observe(this) {
            //重建任务成功后 退出页面
            finish()
        }

        //网络电话接口成功后
        mViewModel.callOutResult.observe(this) {
            //0 未接通 1未接通    -1 空号
            callOutResultByNet = it
            //已拨打+1
            taskInfo.calloutCount++
            if (it == 1) {
                //已接通+1
                taskInfo.switchOnCount++

                mViewModel.commonUILiveData
                    .showDialog.postValue("网络电话呼出中...")
            }
            //通知更新下上面的统计率
            mBinding.data = taskInfo
        }

        mViewModel.getPhoneTaskDetailById(taskInfo.id)

        mViewModel.detailsList.observe(this) {
            adapter.setList(it)
            if (it.isNotEmpty()) {
                curPosition = if (it.none { it.tag == -1 }) {
                    //显示重建任务
                    isAutoCallMode.value = false
                    it.size - 1
                } else {
                    //当前位置等于第一个未拨打的记录
                    it.indexOfFirst { it.tag == -1 }
                }
                LogUtils.e("当前未拨打的index：$curPosition")
            }


        }
        //手动添加号码成功后要刷新一下
        mViewModel.addTaskResult.observe(this) {
            addTaskPhoneDialog.reset()
            mViewModel.getPhoneTaskDetailById(taskInfo.id)
        }

        //手动添加号码成功后要刷新一下
        mViewModel.deleteTaskResult.observe(this) { id ->
            try {
                adapter.remove(adapter.data.single { it.id == id })
            } catch (e: Exception) {
            }
        }


        mViewModel.timeInterval.observe(this) {
            timeInterval = it
            mBinding.tvTimeInterval.text = "${timeInterval}s"
        }

        mViewModel.customerInfo.observe(this, {
            if (it != null) {
                AddOrEditCustomerActivity.start(this, it)
            }
        })
    }


    private fun initRV() {
        adapter = TaskDetailAdapter()
        mBinding.rv.adapter = adapter
        adapter.setOnItemClickListener { adapter, view, position ->
            run {
                val item = adapter.data[position] as TaskDetailInfo
                curPosition = position
                callPhoneByNet(item)
            }
        }

        adapter.addMoreListener { view, item, position ->
            val context = view.context
            TaskPhonePopup(context, {
                DialogTaskPhoneEdit(context, item) {
                    it.id = item.id
                    mViewModel.updateTask(it) {
                        item.name = it.name
                        item.company = it.company
                        item.remark = it.remark
                        item.mobile = it.mobile
                        adapter.notifyDataSetChanged()
                    }
                }.showDialog()
            }, {
                DialogTaskPhoneDelete(context) {
                    mViewModel.deletePhoneTask(item.id, taskInfo.id)
                }.showDialog()
            }, {
                DialogTaskPhoneDetail(context, item) {
                }.showDialog()
            })
                .createPopup<TaskPhonePopup>()
                .showAsDropDown(
                    view, -dp2px(245f), -dp2px(45f)
                )

        }

    }


    lateinit var phoneStateReceiver: PhoneStateReceiver

    //接通时 对应的时间戳 【因现在监听不到接通状态 通过对比通话记录第一条数据判断是否为当前有效通话】
    var openTimeStamp: Long = 0
    var lastPhoneNumber = ""
    private fun registerReceiverByPhoneState() {
        phoneStateReceiver = PhoneStateReceiver(object : PhoneStateReceiver.OnPhoneListener {
            override fun onOpen(phone: String) {
                openTimeStamp = System.currentTimeMillis()
                lastPhoneNumber = phone
            }

            override fun onClose() {
                /** 通过访问通话记录 判断是否是一次有效的通话*/
//                lifecycleScope.launch {
//                    delay(300)
//                    val item = CallUtil.getInstance().getCallHistoryList(1)[0]
//                    if (openTimeStamp - item.timeStamp <= 500) {
//                        //500ms以内的 视为一次有效通话
//
//                        //判断此次通话的状态
//                        if (item.callDuration == 0 || item.callTypeStr == "未接通") {
//                            // 未接通的
//                            dealAutoCallLogic()
//                            ToastUtils.showShort("未接通的")
//                        } else if (item.callDuration >= 0 || item.callTypeStr == "呼出") {
//                            //呼出成功的
//                            dealAutoCallLogic()
//                            ToastUtils.showShort("呼出成功的")
//                        }
//                    } else {
//                        dealAutoCallLogic()
//                        ToastUtils.showShort("取消的")
//                    }
//                }

//                if(adapter.data.any { it.mobile==lastPhoneNumber }){
//                    //挂断电话的时候判断 此号码在任务列表中的 在弹出自动拨号弹窗
                dealAutoCallLogic()
//                }

                dismissWaitLoadingNetDialog()
            }
        })
        val intentFilter = IntentFilter()
        intentFilter.addAction("android.intent.action.PHONE_STATE")
        registerReceiver(phoneStateReceiver, intentFilter)
    }

    //处理自动拨号挂断后的逻辑
    fun dealAutoCallLogic() {
//        if (isAutoCallMode.value!!) {

        // TODO: 2022/1/24 测试的时候 会收到网络电话 以及 登录账号的电话 两次打过来  会造成数组越界
        val item = adapter.data.getOrNull(curPosition)
        LogUtils.e("dealAutoCallLogic  $item")
        item?.let {
            autoCallDialog.showAutoDialog(timeInterval, it.mobile, callOutResultByNet)
        }
//        }
    }


    fun checkPermissions() {
        Acp.getInstance(MyApplication.instance).request(
            AcpOptions.Builder()
                .setPermissions(
                    Manifest.permission.READ_CALL_LOG,
                    Manifest.permission.READ_CONTACTS,
                    Manifest.permission.WRITE_CONTACTS,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.CALL_PHONE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_PHONE_STATE
                ).setDeniedMessage("您拒绝了相关使用权限，app功能将无法正常使用，请去权限授权")
                .build(),
            object : AcpListener {
                override fun onGranted() {


                }

                override fun onDenied(permissions: List<String>) {

                }
            })

    }

    //调用网络拨号
    fun callPhoneByNet(item: TaskDetailInfo) {
        //调用一下接口
        mViewModel.callout(item.id.toString(), taskInfo.id.toString(), item.mobile)
    }

    //调用系统拨号
    fun callPhoneBySystem(item: TaskDetailInfo) {
//        checkAppPermission(Manifest.permission.CALL_PHONE, callBack = {
//            val data = Uri.parse("tel:${item.mobile}")
//            val intent = Intent(Intent.ACTION_CALL)
//            intent.data = data
//            startActivity(intent)
//        })
    }

    override fun onPause() {
        super.onPause()
        dismissWaitLoadingNetDialog()
    }

    //隐藏网络电话加载中弹窗
    private fun dismissWaitLoadingNetDialog() {
        mViewModel.commonUILiveData.dismissDialog.postValue(false)
    }

    override fun onRestart() {
        super.onRestart()
        if (isAddCustomerMode) {
            LogUtils.e("再次显示自动拨号弹窗")
            dealAutoCallLogic()
            isAddCustomerMode = false
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(phoneStateReceiver)
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_task_detail
    }

    companion object {
        fun start(context: Context, info: TaskInfo) {
            context.startActivity(Intent(context, TaskDetailActivity::class.java).apply {
                putExtra("info", info)
            })
        }
    }
}